package com.liang.blog.auth.utils;

import com.liang.blog.common.exception.BlogException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 邮件发送类
 * @Author：YanWenLiang
 * @Date:2024-04-27-20:47
 */
@Component
@Slf4j
public class EmailSendUtil {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String FROM;

    //发送普通文字邮件
    public void sendText(String Subject, String Text, String setFrom, String setTo) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject(Subject);//标题
        simpleMailMessage.setText(Text);//内容
        simpleMailMessage.setFrom(FROM);//发送人邮箱
        simpleMailMessage.setTo(setTo);//发送目的地邮箱
        try {
            javaMailSender.send(simpleMailMessage);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new BlogException("发送失败");
        }
    }

    //发送带页面格式加文件邮件
    public  void sendTexts(String Subject, String Text,Boolean t, String setFrom, String setTo
            ,String attachmentFilename,String filePathName) throws MessagingException {
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);
        helper.setSubject(Subject);//标题
        helper.setText(Text,t);//内容
        helper.setTo(setTo);//目的地邮箱
        helper.addAttachment(attachmentFilename,new File(filePathName));  //图片路径
        javaMailSender.send(mimeMessage);
    }
}
